package pers.cnzdy.tutorial.Chapter9_Perception_Media.Section3_Audio;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.File;

import pers.cnzdy.tutorial.R;

public class MusicPlayerActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "MusicPlayerActivity";
    public final int UPDATE = 1;

    private boolean firstplay = true;
    private Button btnStart, btnStop, btnNext, btnLast;
    private TextView textView;
    private ListView listView;
    private SeekBar seekBar;

    private MusicPlayerService musicService = new MusicPlayerService();

    //实例化一个handler对象
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //更新UI
            int secMax = musicService.player.getDuration(); //最大秒数
            if (msg.what == UPDATE) {
                try {
                    seekBar.setProgress(msg.arg1);
                    textView.setText(setPlayInfo(msg.arg2 / 1000, secMax / 1000));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                seekBar.setProgress(0);
                textView.setText("播放已经停止");
            }
        }
    };

    @Override
    public void run() {
        int position, secMax, seekBarMax;

        while (!Thread.currentThread().isInterrupted()) {
            if (musicService.player != null && musicService.player.isPlaying()) {
                position = musicService.getCurrentProgress();//得到当前歌曲播放进度(秒)
                secMax = musicService.player.getDuration();//最大秒数
                seekBarMax = seekBar.getMax();  //seekBar最大值，算百分比

                Message msg = handler.obtainMessage();//获取一个Message
                msg.arg1 = position * seekBarMax / secMax;//seekBar进度条的百分比
                msg.arg2 = position;
                msg.what = UPDATE;
                handler.sendMessage(msg);
                //  handler.sendEmptyMessage(UPDATE);
                try {
                    Thread.sleep(1000); // 每间隔1秒发送一次更新消息
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //向列表添加MP3名字
    private void setListViewAdapter() {
        String[] str = new String[musicService.musicList.size()];
        int i = 0;

        for (String path : musicService.musicList) {
            File file = new File(path);
            str[i++] = file.getName();
        }

        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1,
                str);
        listView = findViewById(R.id.list_view_music);
        listView.setAdapter(adapter);
    }

    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i(TAG, "申请的权限为：" + permissions[i] + ",申请结果："
                        + grantResults[i]);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                    PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }

        try {
            setListViewAdapter();//添加文件名字
        } catch (Exception e) {
            Log.i(TAG, "读取信息失败");
        }
        textView = findViewById(R.id.text_view_music_info);

        btnStart = findViewById(R.id.btn_star);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (firstplay) {
                        musicService.play();
                        firstplay = false;
                    } else {
                        if (!musicService.player.isPlaying()) {
                            musicService.resume();
                        } else if (musicService.player.isPlaying()) {
                            musicService.pause();
                        }
                    }
                } catch (Exception e) {
                    Log.i(TAG, "播放异常！");
                }

            }
        });

        btnStop = findViewById(R.id.btn_stop);
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    musicService.stop();
                    firstplay = true; //当点击停止按钮时，flag置为1
                    seekBar.setProgress(0);
                    textView.setText("播放已经停止");
                } catch (Exception e) {
                    Log.i(TAG, "停止异常！");
                }

            }
        });

        btnLast = findViewById(R.id.btn_last);
        btnLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    musicService.last();
                } catch (Exception e) {
                    Log.i(TAG, "上一曲异常！");
                }

            }
        });

        btnNext = findViewById(R.id.btn_next);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    musicService.next();
                } catch (Exception e) {
                    Log.i(TAG, "下一曲异常！");
                }

            }
        });

        seekBar = findViewById(R.id.sb);
        seekBar.setOnSeekBarChangeListener(
                new SeekBar.OnSeekBarChangeListener() {
            @Override
            //用于监听SeekBar进度值的改变
            public void onProgressChanged(
                    SeekBar seekBar, int i, boolean b) {
            }

            @Override
            //用于监听SeekBar开始拖动
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            //用于监听SeekBar停止拖动  SeekBar停止拖动后的事件
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                Log.i(TAG, "" + progress);

                int musicMax = musicService.player.getDuration(); //得到该首歌曲最长秒数
                int seekBarMax = seekBar.getMax();
                musicService.player
                        .seekTo(musicMax * progress / seekBarMax);//跳到该曲该秒
            }
        });

        Thread thread = new Thread(this);  // 自动改变进度条的线程
        thread.start();
    }

    //设置当前播放的信息
    private String setPlayInfo(int position, int max) {
        String info = "正在播放:  " + musicService.musicName + "\t\t";
        int playMinutes = 0;

        while (position >= 60) {
            playMinutes++;
            position -= 60;
        }

        String now = (playMinutes < 10 ? "0" + playMinutes : playMinutes) + ":"
                + (position < 10 ? "0" + position : position);

        int mMinutes = 0;
        while (max >= 60) {
            mMinutes++;
            max -= 60;
        }
        String all = (mMinutes < 10 ? "0" + mMinutes : mMinutes) + ":"
                + (max < 10 ? "0" + max : max);

        return info + now + " / " + all;
    }
}
